<template>
  <div class="todo-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <i class="el-icon-document"></i>
        待测评任务
      </h2>
      <p class="page-subtitle">查看所有待完成的心理测评任务</p>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-container">
      <div class="section-header">
        <i class="el-icon-search"></i>
        <span>筛选条件</span>
      </div>
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="任务状态">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择状态"
                style="width: 100%"
                clearable
                @change="handleQuery"
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="进行中" value="ongoing"></el-option>
                <el-option label="已过期" value="expired"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="6">
            <el-form-item label="任务名称">
              <el-input
                v-model="queryParams.taskName"
                placeholder="请输入任务名称"
                clearable
                @change="handleQuery"
              ></el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                @change="handleQuery"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-container">
      <div class="stat-card total">
        <div class="stat-icon">
          <i class="el-icon-data-line"></i>
        </div>
        <div class="stat-content">
          <h3>{{ statistics.total }}</h3>
          <p>总任务数</p>
        </div>
      </div>
      
      <div class="stat-card ongoing">
        <div class="stat-icon">
          <i class="el-icon-time"></i>
        </div>
        <div class="stat-content">
          <h3>{{ statistics.ongoing }}</h3>
          <p>进行中</p>
        </div>
      </div>
      
      <div class="stat-card expired">
        <div class="stat-icon">
          <i class="el-icon-warning"></i>
        </div>
        <div class="stat-content">
          <h3>{{ statistics.expired }}</h3>
          <p>已过期</p>
        </div>
      </div>
      
      <div class="stat-card completion">
        <div class="stat-icon">
          <i class="el-icon-success"></i>
        </div>
        <div class="stat-content">
          <h3>{{ statistics.completionRate }}%</h3>
          <p>完成率</p>
        </div>
      </div>
    </div>

    <!-- 任务列表 -->
    <div class="table-container">
      <div class="section-header">
        <i class="el-icon-s-grid"></i>
        <span>任务列表</span>
        <div class="header-actions">
          <el-button type="text" @click="refreshData">
            <i class="el-icon-refresh"></i>
            刷新
          </el-button>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="filteredTasks"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        
        <el-table-column prop="taskName" label="任务名称" min-width="200" show-overflow-tooltip></el-table-column>
        
        <el-table-column prop="startTime" label="开始时间" width="150" align="center"></el-table-column>
        
        <el-table-column prop="endTime" label="截止时间" width="150" align="center">
          <template slot-scope="scope">
            <span :class="{ 'expired-time': isTaskExpired(scope.row.endTime) }">
              {{ scope.row.endTime }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row)" size="small">
              {{ getStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="progress" label="进度" width="120" align="center">
          <template slot-scope="scope">
            <el-progress
              :percentage="scope.row.progress || 0"
              :stroke-width="8"
              :color="getProgressColor(scope.row.progress)"
            ></el-progress>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleStartTask(scope.row)"
              :disabled="isTaskExpired(scope.row.endTime)"
            >
              {{ isTaskExpired(scope.row.endTime) ? '已过期' : '开始测评' }}
            </el-button>
            <el-button
              size="mini"
              type="info"
              @click="viewTaskDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { getTodoPendingList } from '@/api/system/assess'

export default {
  name: 'TodoList',
  data() {
    return {
      loading: false,
      
      // 查询参数
      queryParams: {
        status: '',
        taskName: '',
        pageNum: 1,
        pageSize: 20
      },
      
      // 日期范围
      dateRange: [],
      
      // 统计数据
      statistics: {
        total: 0,
        ongoing: 0,
        expired: 0,
        completionRate: 0
      },
      
      // 任务列表
      tasks: [],
      total: 0
    }
  },
  
  computed: {
    // 过滤后的任务
    filteredTasks() {
      let filtered = [...this.tasks]
      
      // 状态筛选
      if (this.queryParams.status) {
        if (this.queryParams.status === 'expired') {
          filtered = filtered.filter(task => this.isTaskExpired(task.endTime))
        } else if (this.queryParams.status === 'ongoing') {
          filtered = filtered.filter(task => !this.isTaskExpired(task.endTime))
        }
      }
      
      // 任务名称筛选
      if (this.queryParams.taskName) {
        filtered = filtered.filter(task => 
          task.taskName.includes(this.queryParams.taskName)
        )
      }
      
      // 日期范围筛选
      if (this.dateRange && this.dateRange.length === 2) {
        const [startDate, endDate] = this.dateRange
        filtered = filtered.filter(task => {
          return task.startTime >= startDate && task.startTime <= endDate
        })
      }
      
      return filtered
    }
  },
  
  async mounted() {
    console.log('待测评任务页面初始化中...')
    await this.loadData()
    console.log('待测评任务页面初始化完成！')
  },
  
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true
      try {
        await this.loadTasks()
        this.calculateStatistics()
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请重试')
      } finally {
        this.loading = false
      }
    },
    
    // 加载任务列表
    async loadTasks() {
      try {
        const response = await getTodoPendingList({
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize
        })
        
        if (response.code === 200) {
          // 为每个任务添加进度信息
          this.tasks = response.rows.map(task => ({
            ...task,
            progress: Math.floor(Math.random() * 101) // 模拟进度
          }))
          this.total = response.total
          console.log('加载了', this.tasks.length, '个待测评任务')
        } else {
          this.$message.error(response.msg || '获取任务列表失败')
        }
      } catch (error) {
        console.error('获取任务列表失败:', error)
        this.$message.error('获取任务列表失败')
      }
    },
    
    // 计算统计数据
    calculateStatistics() {
      const total = this.tasks.length
      const expired = this.tasks.filter(task => this.isTaskExpired(task.endTime)).length
      const ongoing = total - expired
      const completionRate = total > 0 ? Math.round((ongoing / total) * 100) : 0
      
      this.statistics = {
        total,
        ongoing,
        expired,
        completionRate
      }
      
      console.log('统计数据:', this.statistics)
    },
    
    // 检查任务是否过期
    isTaskExpired(endTime) {
      if (!endTime) return false
      const now = new Date()
      const endDate = new Date(endTime)
      return now > endDate
    },
    
    // 获取状态标签类型
    getStatusTagType(task) {
      if (this.isTaskExpired(task.endTime)) {
        return 'danger'
      }
      return 'success'
    },
    
    // 获取状态文本
    getStatusText(task) {
      if (this.isTaskExpired(task.endTime)) {
        return '已过期'
      }
      return '进行中'
    },
    
    // 获取进度条颜色
    getProgressColor(progress) {
      if (progress < 30) return '#f56c6c'
      if (progress < 70) return '#e6a23c'
      return '#67c23a'
    },
    
    // 查询
    handleQuery() {
      console.log('执行查询:', this.queryParams, this.dateRange)
      this.calculateStatistics()
    },
    
    // 重置查询
    resetQuery() {
      this.queryParams = {
        status: '',
        taskName: '',
        pageNum: 1,
        pageSize: 20
      }
      this.dateRange = []
      this.handleQuery()
    },
    
    // 刷新数据
    async refreshData() {
      this.$message.info('正在刷新数据...')
      await this.loadData()
      this.$message.success('数据刷新成功')
    },
    
    // 分页大小变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.loadTasks()
    },
    
    // 当前页变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.loadTasks()
    },
    
    // 开始任务
    handleStartTask(task) {
      if (this.isTaskExpired(task.endTime)) {
        this.$message.warning('任务已过期，无法开始测评')
        return
      }
      
      if (!task || !task.id) {
        this.$message.error('任务信息不完整，无法打开')
        return
      }
      
      if (!task.scaleIds) {
        this.$message.error('该任务没有关联量表，无法填写')
        return
      }
      
      // 打开问卷填写页面
      window.open(`/questionnaire?scaleId=${task.scaleIds}&id=${task.id}`)
    },
    
    // 查看任务详情
    viewTaskDetail(task) {
      this.$alert(`任务名称：${task.taskName}\n开始时间：${task.startTime}\n截止时间：${task.endTime}\n任务状态：${this.getStatusText(task)}\n完成进度：${task.progress || 0}%`, '任务详情', {
        confirmButtonText: '确定',
        type: 'info'
      })
    }
  }
}
</script>

<style scoped>
.todo-list-container {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 84px);
}

/* 页面头部 */
.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title i {
  margin-right: 12px;
  color: #409EFF;
}

.page-subtitle {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

/* 筛选区域 */
.filter-container {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  padding: 24px;
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e2e8f0;
  position: relative;
}

.section-header i {
  font-size: 18px;
  color: #409EFF;
  margin-right: 8px;
}

.section-header span {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  letter-spacing: 0.5px;
}

.header-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.section-header::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 60px;
  height: 2px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  border-radius: 1px;
}

/* 统计卡片 */
.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-card.total .stat-icon {
  background: linear-gradient(45deg, #909399, #b1b3b8);
}

.stat-card.ongoing .stat-icon {
  background: linear-gradient(45deg, #67c23a, #85ce61);
}

.stat-card.expired .stat-icon {
  background: linear-gradient(45deg, #f56c6c, #f78989);
}

.stat-card.completion .stat-icon {
  background: linear-gradient(45deg, #409EFF, #36a3f7);
}

.stat-content h3 {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 4px 0;
}

.stat-content p {
  font-size: 14px;
  color: #606266;
  margin: 0;
}

/* 表格容器 */
.table-container {
  background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  margin-bottom: 24px;
}

/* 表格样式 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background: linear-gradient(145deg, #f0f2f5 0%, #e6e8eb 100%);
  color: #2c3e50;
  font-weight: 600;
  text-align: center;
}

.el-table td {
  border-bottom: 1px solid #f0f0f0;
}

.el-table .el-table__row:hover {
  background-color: rgba(64, 158, 255, 0.05);
}

/* 过期时间样式 */
.expired-time {
  color: #f56c6c;
  font-weight: 600;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .todo-list-container {
    padding: 16px;
  }
  
  .stats-container {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .filter-container,
  .table-container {
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .stats-container {
    grid-template-columns: 1fr;
  }
  
  .page-title {
    font-size: 24px;
  }
}
</style>